package com.medical.data.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.medical.data.config.RedisCache;
import com.medical.data.constEnum.CommonEnum;
import com.medical.data.domain.*;
import com.medical.data.exception.MyException;
import com.medical.data.mapper.PatientMapper;
import com.medical.data.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.data.utils.BLUtils;
import com.medical.data.utils.DozerUtils;
import com.medical.data.utils.ResultCode;
import com.medical.data.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cj
 * @since 2024-02-06
 */
@Service
@Slf4j
public class PatientServiceImpl extends ServiceImpl<PatientMapper, Patient> implements PatientService {
    @Autowired
    private ProjectDataService projectDataService;
    @Autowired
    private TokenSerivce tokenSerivce;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private BLUtils blUtils;

    @Autowired
    private FollowPatientService followPatientService;

    @Autowired
    private ProjectTemplateService projectTemplateService;

    @Autowired
    private PatientTemplateService patientTemplateService;

    @Autowired
    private FormDataService formDataService;

    @Autowired
    private UserPermissionService userPermissionService;

    @Override
    public void createPatient(PatientVo patientVo) {
        userPermissionService.getPatientPermission(patientVo.getProjectId());
        User user = tokenSerivce.getUser();
        //首先判断是否存在该项目
        String projectId = patientVo.getProjectId();
        if (ObjectUtils.isEmpty(projectDataService.getProjectDataById(projectId))) {
            throw new MyException(ResultCode.ERROR.getCode(), "项目id不存在");
        }

        //插入patient表中数据
        Patient patient = new Patient();
        BeanUtils.copyProperties(patientVo, patient);
        String doctorId = user.getId();
        patient.setDoctorId(doctorId);
        String hsId = user.getHsId();
        patient.setHospitalId(hsId);
        int insert = this.baseMapper.insert(patient);
        if (insert < 1) {
            throw new MyException(ResultCode.ERROR.getCode(), "插入失败");
        }

        //更新项目表中的病例数量
        projectDataService.updatePatientNumber(projectId);
    }

    @Override
    public Map<String, Object> getPatientPage(GetPatientVo getPatientVo) {
        Integer currentPage = CommonEnum.CURRENT.getValue();
        Integer pageSize = CommonEnum.LIMIT.getValue();
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        //做分页
        if (!ObjectUtils.isEmpty(getPatientVo)) {
            if (StringUtils.isNotBlank(getPatientVo.getName())) {
                wrapper.like(Patient::getPatientName, getPatientVo.getName());
            }
            if (!org.apache.commons.lang3.ObjectUtils.isEmpty(getPatientVo.getCurrentPage())) {
                currentPage = getPatientVo.getCurrentPage();
            }
            if (!org.apache.commons.lang3.ObjectUtils.isEmpty(getPatientVo.getPageSize())) {
                pageSize = getPatientVo.getPageSize();
            }
            wrapper.eq(Patient::getProjectId, getPatientVo.getProjectId());
        }
        /*版本报错*/
        wrapper.orderByDesc(Patient::getCreateTime, Patient::getPatientName);//降序排序
        Page<Patient> page = new Page<>(currentPage, pageSize);
        baseMapper.selectPage(page, wrapper);
        List<Patient> patients = page.getRecords();
        List<PatientVo> patientVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(patients)) {
            patientVos = DozerUtils.mapList(patients, PatientVo.class);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        map.put("current", page.getCurrent());
        map.put("patientVos", patientVos);
        return map;

    }

    @Override
    public void addPatient(PatientVo patientVo) {
        userPermissionService.getPatientPermission(patientVo.getProjectId());
        //在新增病历时，需要查询该项目下是否有节点
        Boolean exitTemplate = projectTemplateService.isExitTemplate(patientVo.getProjectId());
        if (!exitTemplate)
            throw new MyException(ResultCode.ERROR.getCode(), "请先新增节点和表单");
        User user = tokenSerivce.getUser();
        if (ObjectUtils.isEmpty(user.getHsId()))
            throw new MyException(ResultCode.ERROR.getCode(), "请医生选择医院");
        //首先查询该项目下该患者是否已存在
        Patient patient1 = baseMapper.selectOne(Wrappers.<Patient>lambdaQuery().eq(Patient::getDoctorId, user.getId())
                .eq(Patient::getProjectId, patientVo.getProjectId())
                .eq(Patient::getIdCard, patientVo.getIdCard()));
        if (!ObjectUtils.isEmpty(patient1)) {
            throw new MyException(ResultCode.PATIENTEXIT.getCode(), ResultCode.PATIENTEXIT.getDesc());
        }
        Patient patient = new Patient();
        BeanUtils.copyProperties(patientVo, patient);
        patient.setPatientAge(getAgeFromIdCard(patientVo.getIdCard()));
        patient.setDoctorId(user.getId());
        patient.setHospitalId(user.getHsId());
        patient.setRecordNumber(blUtils.BLCreate());
        patient.setFollowUpTime(new Date());
        //病历号生成
        int insert = this.baseMapper.insert(patient);
        if (insert < 1)
            throw new MyException(ResultCode.ERROR.getCode(), "新增病例失败");
        //创建时默认开启随访
        redisCache.deleteObject(patient.getRecordNumber());
        //更新项目表中的病例数量
        projectDataService.updatePatientNumber(patientVo.getProjectId());
        //更新患者与节点之间的关系
        patientTemplateService.addPatientTemplate(patientVo.getProjectId(), patient.getId());
        //默认开启随访
        updateIsFollow(patient.getId(), true);
        String projectId = patient.getProjectId();
        List<FormTemplate> formTemplates = projectTemplateService.getFollowNodesByProjectId(projectId);
        Date followUpTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (FormTemplate formTemplate : formTemplates) {
            FollowUpPatient followUpPatient = new FollowUpPatient();
            followUpPatient.setName(patient.getPatientName());
            followUpPatient.setPatientId(patient.getId());
            followUpPatient.setProjectId(patient.getProjectId());
            followUpPatient.setIdCard(patient.getIdCard());
            followUpPatient.setFollowUpTime(formTemplate.getFollowUpTime());
            followUpPatient.setDiseaseType(patient.getDiseaseType());
            followUpPatient.setDoctorName(user.getNickName());
            followUpPatient.setDoctorId(user.getId());
            followUpPatient.setInTime(patient.getInTime());
            int daysToAdd = Integer.parseInt(formTemplate.getFollowUpTime()); // 将 String 类型的天数转换为整数
            long timeInMillis = followUpTime.getTime() + daysToAdd * 24 * 60 * 60 * 1000; // 计算新的随访时间的毫秒数
            Date newFollowUpTime = new Date(timeInMillis); // 创建新的随访时间对象
            String dateString = sdf.format(newFollowUpTime);
            followUpPatient.setFollowUpTime(dateString);
            followUpPatient.setOutTime(patient.getOutTime());
            followUpPatient.setStatus(false);
            followUpPatient.setNodeId(formTemplate.getId());
            followUpPatient.setNodeName(formTemplate.getName());
            followUpPatient.setIsDown(false);
            followUpPatient.setHospitalName(patient.getHospitalId());
            followUpPatient.setPhone(patient.getPatientPhone());
            followUpPatient.setCode(patient.getRecordNumber());
            followPatientService.addPatient(followUpPatient);
        }
    }

    //根据身份证号算年龄
    public int getAgeFromIdCard(String idCard) {
        String birthdayStr = idCard.substring(6, 14); // 从身份证号码中提取出生日期部分
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date birthday;
        try {
            birthday = sdf.parse(birthdayStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return -1; // 解析出生日期失败，返回 -1 表示未知年龄
        }

        Calendar birthCal = Calendar.getInstance();
        birthCal.setTime(birthday);
        Calendar nowCal = Calendar.getInstance();

        int age = nowCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);
        // 如果当前月份小于出生月份，或者当前月份等于出生月份但是当前日期小于出生日期，则年龄减一
        if ((nowCal.get(Calendar.MONTH) < birthCal.get(Calendar.MONTH))
                || (nowCal.get(Calendar.MONTH) == birthCal.get(Calendar.MONTH)
                && nowCal.get(Calendar.DAY_OF_MONTH) < birthCal.get(Calendar.DAY_OF_MONTH))) {
            age--;
        }
        return age;
    }

    public void openFollowUp(OpenFollowUpVo openFollowUpVo) {
/*
        Patient patient = new Patient();
        openFollowUpVo.setFollowUpTime(new Date());
        openFollowUpVo.setIsFollowUp(true);
        BeanUtils.copyProperties(openFollowUpVo,patient);
        int i = baseMapper.updateById(patient);
        if (i<1)
            throw new MyException(ResultCode.ERROR.getCode(), "开启随访失败");
*/
        userPermissionService.getFollowUpPermission(getProjectIdByPatientId(openFollowUpVo.getPatientId()));
        User user = tokenSerivce.getUser();
        Boolean isFollowUp = openFollowUpVo.getIsFollowUp();
        //TODO 如果是关闭随访
        if (!isFollowUp) {
            //更新患者表is_follow_time字段
            updateIsFollow(openFollowUpVo.getPatientId(), openFollowUpVo.getIsFollowUp());
            //更新随访患者表
            followPatientService.updateIsDown(openFollowUpVo.getPatientId(), true);

            return;
        }

        //TODO 是否是第一次开启随访
        //如果是的话，就执行插入，直接插入到随访患者表，不在患者表里做更新，之前功能重复，复杂
        if (!followPatientService.isExistPatient(openFollowUpVo.getPatientId())) {
            //更新患者表is_follow_time字段
            updateIsFollow(openFollowUpVo.getPatientId(), openFollowUpVo.getIsFollowUp());
            String projectId = patientTemplateService.getProjectByPatient(openFollowUpVo.getPatientId());
            List<FormTemplate> formTemplates = projectTemplateService.getFollowNodesByProjectId(projectId);
            Patient patient = getPatientById(openFollowUpVo.getPatientId());
            Date followUpTime = openFollowUpVo.getFollowUpTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (FormTemplate formTemplate : formTemplates) {
                FollowUpPatient followUpPatient = new FollowUpPatient();
                followUpPatient.setName(patient.getPatientName());
                followUpPatient.setPatientId(patient.getId());
                followUpPatient.setProjectId(patient.getProjectId());
                followUpPatient.setIdCard(patient.getIdCard());
                followUpPatient.setFollowUpTime(formTemplate.getFollowUpTime());
                followUpPatient.setDiseaseType(patient.getDiseaseType());
                followUpPatient.setDoctorName(user.getNickName());
                followUpPatient.setDoctorId(user.getId());
                followUpPatient.setInTime(patient.getInTime());
                int daysToAdd = Integer.parseInt(formTemplate.getFollowUpTime()); // 将 String 类型的天数转换为整数
                long timeInMillis = followUpTime.getTime() + daysToAdd * 24 * 60 * 60 * 1000; // 计算新的随访时间的毫秒数
                Date newFollowUpTime = new Date(timeInMillis); // 创建新的随访时间对象
                String dateString = sdf.format(newFollowUpTime);
                followUpPatient.setFollowUpTime(dateString);
                followUpPatient.setOutTime(patient.getOutTime());
                followUpPatient.setStatus(false);
                followUpPatient.setNodeId(formTemplate.getId());
                followUpPatient.setNodeName(formTemplate.getName());
                followUpPatient.setIsDown(false);
                followUpPatient.setHospitalName(patient.getHospitalId());
                followUpPatient.setPhone(patient.getPatientPhone());
                followUpPatient.setCode(patient.getRecordNumber());
                followPatientService.addPatient(followUpPatient);
            }
        }
        //不是第一次开启随访
        else {
            //更新患者表is_follow_time字段
            updateIsFollow(openFollowUpVo.getPatientId(), openFollowUpVo.getIsFollowUp());

            Date followUpTime = openFollowUpVo.getFollowUpTime();
            Patient patient1 = getPatientById(openFollowUpVo.getPatientId());
            //随访时间未改变,只修改开启关闭状态isDown
            if (followUpTime.equals(patient1.getFollowUpTime())) {
                followPatientService.updateIsDown(openFollowUpVo.getPatientId(), false);
            }
            //随访时间改变,修改开启关闭状态isDown以及随访时间，还要更新患者表中的随访时间
            else {
                updateFollowUpTime(openFollowUpVo.getPatientId(), openFollowUpVo.getFollowUpTime());
                followPatientService.updateIsDownAndTime(openFollowUpVo.getPatientId(), openFollowUpVo.getFollowUpTime(), false);
            }
        }
/*        //1.根据患者id找到项目id，把该项目下所有的随访节点的随访时间提取到患者的followUpJson中
        String projectId = patientTemplateService.getProjectByPatient(openFollowUpVo.getPatientId());
        //2.找到该项目下所有的随访节点
        List<FormTemplate> formTemplates = projectTemplateService.getFollowNodesByProjectId(projectId);
        //提取出所有节点的随访时间
        List<String> followUpTimesList = new ArrayList<>();
        List<String> followUPNodeList = new ArrayList<>();
        for (FormTemplate formTemplate : formTemplates) {
            String followUpTime = formTemplate.getFollowUpTime();
            String followUpNode = formTemplate.getId();
            followUpTimesList.add(followUpTime);
            followUPNodeList.add(followUpNode);
        }
        // 使用 Stream API 将 List 转换为逗号分隔的字符串
        String followUpTimesString = followUpTimesList.stream().collect(Collectors.joining(","));
        String followUpNodesString = followUPNodeList.stream().collect(Collectors.joining(","));
        BeanUtils.copyProperties(openFollowUpVo, patient);
        patient.setFollowUpTimeJson(followUpTimesString);
        patient.setFollowUpNodeJson(followUpNodesString);
        patient.setId(openFollowUpVo.getPatientId());
        patient.setFollowUpTime(openFollowUpVo.getFollowUpTime());
        //把具体的随访时间加到字段中
        Date followUpTime = patient.getFollowUpTime();
        String followUpTimeJson = patient.getFollowUpTimeJson();
        String[] daysArray = followUpTimeJson.split(",");

        List<Date> newFollowUpTimes = new ArrayList<>();
        for (String days : daysArray) {
            int daysToAdd = Integer.parseInt(days);
            long timeInMillis = followUpTime.getTime() + daysToAdd * 24 * 60 * 60 * 1000;
            Date newFollowUpTime = new Date(timeInMillis);
            newFollowUpTimes.add(newFollowUpTime);
        }

        List<String> stringList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (Date date : newFollowUpTimes) {
            String dateString = sdf.format(date);
            stringList.add(dateString);
        }
        String jsonString = String.join(",", stringList);
        patient.setNewFollowUpTimes(String.join(",", stringList));
        int i = baseMapper.updateById(patient);
        if (i < 1)
            throw new MyException(ResultCode.ERROR.getCode(), "开启随访失败");
        //在患者节点表里找到要填写的节点，获取节点id和节点名称
        //
        //更新随访患者表
        followPatientService.addFollowPatient(openFollowUpVo, jsonString, followUpNodesString);*/
    }

    public Map<String, Object> getPatientByProject(QueryPatientVo queryPatientVo) {
        User user = tokenSerivce.getUser();
        Map<String, Object> result = new HashMap<>();
        //首选获取该项目下所有的节点名字 TODO 目前不考虑项目公开的问题
        List<FormTemplate> formTemplates = projectTemplateService.getAllNodes(queryPatientVo.getProjectId());
        //获取节点名字
        //List<String> fileds = new ArrayList<>();
        //fileds = formTemplates.stream().map(FormTemplate::getName).collect(Collectors.toList());
        result.put("fileds", formTemplates);
        //2.获取患者数据
        Integer current = CommonEnum.OTHER_PATIENT_CURRENT.getValue();
        Integer limit = CommonEnum.OTHER_PATIENT_LIMIT.getValue();
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        //做分页
        if (StringUtils.isNotBlank(queryPatientVo.getHospitalId())) {
            wrapper.eq(Patient::getHospitalId, queryPatientVo.getHospitalId());
        } else {
            wrapper.eq(Patient::getHospitalId, user.getHsId());
        }
        if (!ObjectUtils.isEmpty(queryPatientVo.getBeginTime())) {
            wrapper.ge(Patient::getCreateTime, queryPatientVo.getBeginTime());
        }
        if (!ObjectUtils.isEmpty(queryPatientVo.getEndTime())) {
            wrapper.le(Patient::getCreateTime, queryPatientVo.getEndTime());
        }
        if (!ObjectUtils.isEmpty(queryPatientVo.getCurrent())) {
            current = queryPatientVo.getCurrent();
        }
        if (!ObjectUtils.isEmpty(queryPatientVo.getLimit())) {
            limit = queryPatientVo.getLimit();
        }
        if (!ObjectUtils.isEmpty(queryPatientVo.getPatientName())) {
            wrapper.eq(Patient::getPatientName, queryPatientVo.getPatientName());
        }
        if (!ObjectUtils.isEmpty(queryPatientVo.getIdCard())) {
            wrapper.eq(Patient::getIdCard, queryPatientVo.getIdCard());
        }
        if (!ObjectUtils.isEmpty(queryPatientVo.getRecordNumber())) {
            wrapper.eq(Patient::getRecordNumber, queryPatientVo.getRecordNumber());
        }
        wrapper.eq(Patient::getProjectId, queryPatientVo.getProjectId())
                .eq(Patient::getDoctorId, user.getId())
                .orderByDesc(Patient::getCreateTime);
        Page<Patient> page = new Page<>(current, limit);
        baseMapper.selectPage(page, wrapper);
        result.put("total", page.getTotal());
        result.put("limit", limit);
        result.put("current", current);
        List<Patient> patients = page.getRecords();
        if (CollectionUtils.isEmpty(patients))
            return result;
        List<QueryPatientResultVo> patientResultVoList = DozerUtils.mapList(patients, QueryPatientResultVo.class);
        for (QueryPatientResultVo patient : patientResultVoList) {
            //时间格式转换
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(patient.getFollowUpTime());
            patient.setFinalTime(formattedDate);
            List<DataProportionVo> dataProportionVos = new ArrayList<>();
            for (FormTemplate formTemplate : formTemplates) {
                List<PatientTemplate> patientTemplates = patientTemplateService.getProportionByNodeId(formTemplate.getId(), user.getId(), queryPatientVo.getProjectId(), patient.getId());
                if (CollectionUtils.isEmpty(patientTemplates)) {
                    DataProportionVo dataProportionVo = new DataProportionVo().setNodeId(formTemplate.getId()).setProportion("0");
                    ArrayList<DataProportionVo> list = new ArrayList<>();
                    list.add(dataProportionVo);
                    patient.setDataProportionVos(list);
                    log.info("=======>{}", patient);
                    continue;
                }
                //List<DataProportionVo> dataProportionVos = new ArrayList<>();
                for (PatientTemplate patientTemplate : patientTemplates) {
                    DataProportionVo dataProportionVo = new DataProportionVo().setNodeId(formTemplate.getId());
                    //计算比例
                    Integer total = patientTemplate.getFinishNumber() + patientTemplate.getNotFinishNumber();
                    Double proportion;
                    if (total != 0) {
                        proportion = Double.valueOf(patientTemplate.getFinishNumber()) / total;
                    } else {
                        proportion = 0.0;
                    }
                    dataProportionVo.setProportion(proportion.toString());
                    dataProportionVos.add(dataProportionVo);
                }
                patient.setDataProportionVos(dataProportionVos);

            }
        }
        result.put("patients", patientResultVoList);
        return result;
    }

    @Override
    public Date getFollowTime(String patientId) {
        Patient patient = new Patient();
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Patient::getId, patientId);
        patient = this.baseMapper.selectOne(wrapper);
        return patient.getFollowUpTime();
    }

    @Override
    public Patient getPatientById(String patientId) {
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Patient::getId, patientId);
        return this.baseMapper.selectOne(wrapper);
    }

    @Override
    public List<Patient> getPatientsByIds(List<String> list) {
        List<Patient> list1 = new ArrayList<>();
        for (String patientId : list) {
            list1.add(getPatientById(patientId));
        }
        return list1;
    }

    @Override
    public void updateIsFollow(String patientId, Boolean isFollowUp) {
        userPermissionService.getFollowUpPermission(getProjectIdByPatientId(patientId));
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Patient::getId, patientId);
        Patient patient = this.baseMapper.selectOne(wrapper);
        patient.setIsFollowUp(isFollowUp);
        int update = this.baseMapper.updateById(patient);
        if (update < 1) {
            throw new MyException(ResultCode.ERROR.getCode(), "更新随访开启状态失败");
        }
    }

    @Override
    public boolean isExistInProject(String projectId) {
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Patient::getProjectId, projectId);

        List<Patient> patients = this.baseMapper.selectList(wrapper);
        if (patients.size() == 0) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void updateFollowUpTime(String patientId, Date date) {
        userPermissionService.getFollowUpPermission(getProjectIdByPatientId(patientId));
        LambdaUpdateWrapper<Patient> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Patient::getId, patientId)
                .set(Patient::getFollowUpTime, date);
        int update = this.baseMapper.update(null, wrapper);
        if (update < 1) {
            throw new MyException(ResultCode.ERROR.getCode(), "更新患者表随访时间失败");
        }
    }

    @Override
    public int getPatientNumber() {
        User user = tokenSerivce.getUser();
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Patient::getDoctorId, user.getId());
        return this.baseMapper.selectList(wrapper).size();

    }

    @Override
    public int getTodayPatientNumber() {

        User user = tokenSerivce.getUser();
        LocalDate today = LocalDate.now();
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Patient::getDoctorId, user.getId())
                .apply("DATE(create_time) = DATE({0})", today); // 使用DATE()函数比较日期部分;;
        return this.baseMapper.selectList(wrapper).size();
    }

    @Override
    public void deleteById(String patientIds) {

        String[] patientIdsArray = patientIds.split(",");
        List<String> patientIdsList = Arrays.asList(patientIdsArray);
        for (String patientId : patientIdsList) {
            LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Patient::getId, patientId);
            int delete = this.baseMapper.delete(wrapper);
            if (delete < 1) {
                throw new MyException(ResultCode.ERROR.getCode(), "删除患者节点表数据失败");
            }
            patientTemplateService.deletePatientTemplateById(patientId);
            formDataService.deleteDataById(patientId);
            followPatientService.deleteFollowPatientById(patientId);
        }
    }

    @Override
    public List<PatientAgeVo> getPatientAge() {
        User user = tokenSerivce.getUser();
        List<PatientAgeVo> list = new ArrayList<>();

        LambdaQueryWrapper<Patient> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Patient::getDoctorId, user.getId())
                .between(Patient::getPatientAge, 0, 18);
        PatientAgeVo patientAgeVo1 = new PatientAgeVo();
        patientAgeVo1.setName("0-18");
        patientAgeVo1.setValue(this.baseMapper.selectList(wrapper1).size());
        list.add(patientAgeVo1);

        LambdaQueryWrapper<Patient> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Patient::getDoctorId, user.getId())
                .between(Patient::getPatientAge, 19, 30);
        PatientAgeVo patientAgeVo2 = new PatientAgeVo();
        patientAgeVo2.setName("19-30");
        patientAgeVo2.setValue(this.baseMapper.selectList(wrapper2).size());
        list.add(patientAgeVo2);

        LambdaQueryWrapper<Patient> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(Patient::getDoctorId, user.getId())
                .between(Patient::getPatientAge, 31, 45);
        PatientAgeVo patientAgeVo3 = new PatientAgeVo();
        patientAgeVo3.setName("31-45");
        patientAgeVo3.setValue(this.baseMapper.selectList(wrapper3).size());
        list.add(patientAgeVo3);

        LambdaQueryWrapper<Patient> wrapper4 = new LambdaQueryWrapper<>();
        wrapper4.eq(Patient::getDoctorId, user.getId())
                .between(Patient::getPatientAge, 46, 60);
        PatientAgeVo patientAgeVo4 = new PatientAgeVo();
        patientAgeVo4.setName("46-60");
        patientAgeVo4.setValue(this.baseMapper.selectList(wrapper4).size());
        list.add(patientAgeVo4);

        LambdaQueryWrapper<Patient> wrapper5 = new LambdaQueryWrapper<>();
        wrapper5.eq(Patient::getDoctorId, user.getId())
                .between(Patient::getPatientAge, 61, 80);
        PatientAgeVo patientAgeVo5 = new PatientAgeVo();
        patientAgeVo5.setName("61-80");
        patientAgeVo5.setValue(this.baseMapper.selectList(wrapper5).size());
        list.add(patientAgeVo5);

        return list;
    }

    @Override
    public String getProjectIdByPatientId(String patientId) {
        LambdaQueryWrapper<Patient> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Patient::getId, patientId);
        return this.baseMapper.selectOne(wrapper).getProjectId();
    }
}
